# -*- coding: utf-8 -*-

from nmj.scanners.movie import NMJImage, NMJMovie
from nmj.sqlite.nmj_db import NMJ_MOVIE_TYPE
from themoviedb import tmdb
import locale
import logging

_LOGGER = logging.getLogger(__name__)

def to_unicode(text):
	if isinstance(text, unicode):
		return text

	if hasattr(text, '__unicode__'):
		return text.__unicode__()

	text = str(text)

	try:
		return unicode(text, 'utf-8')
	except UnicodeError:
		pass

	try:
		return unicode(text, locale.getpreferredencoding())
	except UnicodeError:
		pass

	return unicode(text, 'latin1')

BACKDROP_SIZES = ["original", "w1280", "poster", "thumb"]
POSTER_SIZES = ["mid", "w342", "cover", "w154", "thumb"]
def get_largest(image, size_list):
	for size in size_list:
		if size in image:
			return image[size]

class TMDBMovie(NMJMovie):
	def __init__(self, tmdb_id, imdb_id, title,
			synopsis="", short_synopsis="", posters=None, fanarts=None,
			genres=None, cast=None, show_type=NMJ_MOVIE_TYPE, rating=0.0):
		NMJMovie.__init__(self, title, synopsis=synopsis, short_synopsis=short_synopsis,
			posters=posters, fanarts=fanarts, genres=genres, cast=cast, show_type=show_type, rating=rating)
		self.tmdb_id = tmdb_id
		self.imdb_id = imdb_id

class TMDbScanner(object):
	def __init__(self):
		tmdb.config = {}
		tmdb.config['apikey'] = "104e67f6ef05585ed35eec68f5cae0bf"
		tmdb.config['urls'] = {}
		tmdb.config['urls']['movie.search'] = "http://api.themoviedb.org/2.1/Movie.search/fr/xml/%(apikey)s/%%s" % (tmdb.config)
		tmdb.config['urls']['movie.getInfo'] = "http://api.themoviedb.org/2.1/Movie.getInfo/fr/xml/%(apikey)s/%%s" % (tmdb.config)
		tmdb.config['urls']['media.getInfo'] = "http://api.themoviedb.org/2.1/Media.getInfo/fr/xml/%(apikey)s/%%s/%%s" % (tmdb.config)
		tmdb.config['urls']['imdb.lookUp'] = "http://api.themoviedb.org/2.1/Movie.imdbLookup/fr/xml/%(apikey)s/%%s" % (tmdb.config)
		self._webapi = tmdb.MovieDb()

	def to_nmj_movie(self, *web_results):
		results = []
		for movie in web_results:
			posters = []
			fanarts = []
			for image in movie["images"]:
				if image["type"] == "poster":
					posters.append(NMJImage(get_largest(image, POSTER_SIZES), image.get("thumb", None)))
				else:
					fanarts.append(NMJImage(get_largest(image, BACKDROP_SIZES), image.get("thumb", None)))
			results.append(TMDBMovie(
				tmdb_id=movie["id"],
				imdb_id=movie["imdb_id"],
				title=movie["name"],
				synopsis=movie["overview"],
				short_synopsis="",
				posters=posters,
				fanarts=fanarts,
				genres=movie.get("categories", {"genre" : {}}).get("genre", {}).keys(),
				cast=movie.get("cast", {}),
				rating=float(movie["rating"]),
			))
		return results

	def search(self, string, **_kwargs):
		try:
			movies = self.to_nmj_movie(*self._webapi.search(to_unicode(string)))
			for movie in movies:
				movie.get_media = self.get_media(movie.tmdb_id)
			return movies
		except:
			_LOGGER.exception("Failed to find data for movie %s", string)
			return []

	def get_media(self, movie_id, get_first_result=True):
		def fetch():
			try:
				results = self.to_nmj_movie(self._webapi.getMovieInfo(id=movie_id))
			except tmdb.TmdHttpError:
				_LOGGER.exception("Cannot retrieve movie info")
				raise
			if get_first_result:
				return results[0]
			else:
				return results
		return fetch

if __name__ == "__main__":
	scanner = TMDbScanner()
	results = scanner.search("retour vers le futur 3")
	result = scanner.get_media(results[0].tmdb_id)()
	print result


